package com.pmcc.cj.service.threads;

import com.google.gson.Gson;
import com.pmcc.cj.entity.*;
import com.pmcc.cj.repository.*;
import com.pmcc.core.entity.SmsRecord;
import com.pmcc.core.repository.SmsRecordRepository;
import com.pmcc.utils.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.beans.beancontext.BeanContext;
import java.util.*;

/**
 * 用于机手接单用
 * Created by tomas on 2020/9/23.
 */
@Transactional
@Service
public class MyThreadRobot implements Runnable {
    private SmsRecordRepository smsRecordRepository;
    private List<CjCustomer> list;
    private List<CjOrder> orderList;
    private CjTaskRepository cjTaskRepository;
    private CjCommodityYunRepository  yunRepository;
    private CjOrderDetailRepository detailRepository;
    private CjOrderRepository cjOrderRepository;

    public MyThreadRobot(SmsRecordRepository smsRecordRepository, List<CjCustomer> list, List<CjOrder> orderList, CjTaskRepository cjTaskRepository, CjCommodityYunRepository yunRepository, CjOrderDetailRepository detailRepository, CjOrderRepository cjOrderRepository) {
        this.smsRecordRepository = smsRecordRepository;
        this.list = list;
        this.orderList = orderList;
        this.cjTaskRepository = cjTaskRepository;
        this.yunRepository = yunRepository;
        this.detailRepository = detailRepository;
        this.cjOrderRepository = cjOrderRepository;
    }

    public MyThreadRobot() {
    }

    @Override
    public void run() {
        Map<String,Boolean> map = new HashMap<>();
        for(CjOrder order: orderList){
            map.put(order.getId(),false);
        }
        //先把当前所有机手id存入二级订单表
        if(list != null && list.size()>0){
            String str="";
            for(CjCustomer customer: list){
                str+=(customer.getId()+",");
            }
            for(CjOrder order: orderList){
                order.setRobotThread(str.substring(0,str.length()-1));
                cjOrderRepository.saveAndFlush(order);
            }
        }
        while (true){
            try {
                if(list != null && list.size()>0){
                    for(CjCustomer customer : list){//此处customer是机手
                        for(CjOrder order: orderList){
                            CjTask task = cjTaskRepository.findByOrderId(order.getId());
                            if(task != null){
                                if(task.getFettleType() ==1){
                                    map.put(order.getId(),true);
                                }else {
//                                    task.setOrderId(order.getId());
//                                    task.setFettle(1);
                                    task.setRobotId(customer.getId());
                                    task.setCreateTime(new Date());
//                                    task.setCustomerId(order.getEmployeeId());
//                                    task.setCustomerName(order.getLinkman());
//                                    task.setCellphone(order.getCellphone());
//                                    task.setFettleTask(0);
//                                    task.setFettleType(0);

//                                    task.setProvince(customer.getProvince());
//                                    task.setCity(customer.getCity());
//                                    task.setCounty(customer.getCounty());
//                                    task.setTownship(customer.getTownship());
//                                    task.setVillage(customer.getVillage());
//                                    task.setAddress(order.getAddress());

//                                    task.setSalesmanId(order.getRetailerId());
//                                    task.setMoney(order.getPrice());
//                                    task.setNumber(order.getCommodityCount()+0.0);
//                                    task.setTotalMoney(order.getMoney());
//                                    task.setBeginTime(DateUtil.addDay(new Date(),2));
                                    //根据订单查询作物类型，药剂类型
//                                    CjCommodityYun yun= yunRepository.findById(order.getYunId());
//                                    task.setCropType(yun.getProductName());
//                                    task.setMedicineType(yun.getTypeName());
//                                    task.setCycleTime(2);
//                                    task.setYunId(order.getYunId());
//                                    task.setYunName(yun.getName());
//                                    List<CjOrderDetail> details=detailRepository.findByOrderId(order.getId());
//                                    Gson gson=new Gson();
//                                    task.setYunDetail(gson.toJson(details));
                                    cjTaskRepository.saveAndFlush(task);
                                    if(customer.getRobotFlag() ==  0){//需要推送的才推送，不需要的不推送
                                        //每个订单每人每天只发两次短信推送
                                        List<SmsRecord> llss=smsRecordRepository.findByCustomerIdAndTaskIdAndCreateTimeBetween(customer.getId(),task.getId(),DateUtil.getStartDayTime(new Date()),DateUtil.getEndDayTime(new Date()));
                                        if(llss == null || llss.size()<3){
                                            String message = "{\"name\":\""+customer.getWechatName()+"\"}";
                                            SmsRecord smsRecord=SmsSendUtil.sendSmsCode2(customer.getCellphone(),message);
                                            smsRecord.setTaskId(task.getId());
                                            smsRecord.setCustomerId(customer.getId());
                                            smsRecordRepository.saveAndFlush(smsRecord);
                                        }
                                    }
                                }
                            }else {
                                task = new CjTask();
                                task.setOrderId(order.getId());
                                task.setFettle(1);
                                task.setRobotId(customer.getId());
                                task.setCustomerId(order.getEmployeeId());
                                task.setCustomerName(order.getLinkman());
                                task.setCellphone(order.getCellphone());
                                task.setFettleTask(0);
                                task.setFettleType(0);
                                List<Map<String,String>> lt=AddressResolutionUtil.addressResolution(order.getAddress());
                                if(lt != null && lt.size()>0){
                                    task.setProvince(lt.get(0).get("province"));
                                    task.setCity(lt.get(0).get("city"));
                                    task.setCounty(lt.get(0).get("county"));
                                    task.setTownship(lt.get(0).get("town"));
                                    task.setVillage(lt.get(0).get("village"));
                                }

                                task.setAddress(order.getAddress());

                                task.setSalesmanId(order.getRetailerId());
                                task.setMoney(order.getPrice());
                                task.setNumber(order.getCommodityCount()+0.0);
                                task.setTotalMoney(order.getMoney());
                                task.setCreateTime(new Date());
                                task.setBeginTime(DateUtil.addDay(new Date(),2));
                                //根据订单查询作物类型，药剂类型
                                CjCommodityYun yun= yunRepository.findById(order.getYunId());
                                task.setCropType(yun.getProductName());
                                task.setMedicineType(yun.getTypeName());
                                task.setCycleTime(2);
                                task.setYunId(order.getYunId());
                                task.setYunName(yun.getName());
                                task.setRobotFlag("0");
                                List<CjOrderDetail> details=detailRepository.findByOrderId(order.getId());
                                Gson gson=new Gson();
                                task.setYunDetail(gson.toJson(details));
                                cjTaskRepository.saveAndFlush(task);
                                if(customer.getRobotFlag() ==0){//需要推送的才推送，不需要的不推送
                                    //每个订单每人每天只发两次短信推送
                                    List<SmsRecord> llss=smsRecordRepository.findByCustomerIdAndTaskIdAndCreateTimeBetween(customer.getId(),task.getId(),DateUtil.getStartDayTime(new Date()),DateUtil.getEndDayTime(new Date()));
                                    if(llss == null || llss.size()<3){
                                        String message = "{\"name\":\""+customer.getWechatName()+"\"}";
                                        SmsRecord smsRecord=SmsSendUtil.sendSmsCode2(customer.getCellphone(),message);
                                        smsRecord.setTaskId(task.getId());
                                        smsRecord.setCustomerId(customer.getId());
                                        smsRecordRepository.saveAndFlush(smsRecord);
                                    }
                                }
                            }
                        }
                        Set<String>  set=map.keySet();
                        boolean isTrue=true;
                        for(String str:set){
                            if(!map.get(str)){
                                isTrue=false;
                                break;
                            }
                        }
                        if(isTrue){
                            return;
                        }
                        Thread.sleep(60*60*1*1000);//60*60*1s=1h
                    }
                    //如果操作结束还没有人接单则重复以上操作。
                }
            }catch (Exception e){
                return;
            }
        }
    }
}
